#include "StdAfx.h"
#include "FileManager.h"


BEGIN_MESSAGE_MAP(CFileManager, CCmdTarget)
	ON_COMMAND(ID_FILE_NEW, OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, OnFileOpen)
	ON_COMMAND(ID_FILE_SAVE, OnFileSave)
	ON_COMMAND(ID_FILE_SAVE_AS, OnFileSaveAs)
END_MESSAGE_MAP()


int CFileManager::AskToSave()
{
	CString strFormat;
	VERIFY(strFormat.LoadString(AFX_IDP_ASK_TO_SAVE));

	CString strPrompt;
	strPrompt.Format(strFormat, (LPCTSTR)m_strTitle);
	return AfxMessageBox(strPrompt, MB_ICONWARNING | MB_YESNOCANCEL);
}

VOID CFileManager::ClearDocument()
{
	m_bModified = FALSE;
	m_bNamed = FALSE;

	VERIFY(m_strTitle.LoadString(IDS_DOC_TITLE));

	m_rDocumentManager.CloseAllViews();
	m_rDocument.Clear();
}


CString CFileManager::GetFolderPath(CString &strFilePath)
{
	int iLastSlashIndex = strFilePath.ReverseFind(_T('/'));
	int iLastBackslashIndex = strFilePath.ReverseFind(_T('\\'));

	int iLastSeparator;
	if (iLastSlashIndex > iLastBackslashIndex)
	{
		iLastSeparator = iLastSlashIndex;
	}
	else
	{
		iLastSeparator = iLastBackslashIndex;
	}

	return strFilePath.Left(iLastSeparator + 1);
}


CFileManager::CFileManager(CResourceDocument &a_rDocument, CDocumentManager &a_rDocumentManager) :
m_rDocument(a_rDocument),
m_rDocumentManager(a_rDocumentManager),
m_bModified(FALSE),
m_bNamed(FALSE)
{
	VERIFY(m_strTitle.LoadString(IDS_DOC_TITLE));
}


BOOL CFileManager::CreateNew()
{
	if (m_bModified)
	{
		int nResponse = AskToSave();
		if (nResponse == IDYES)
		{
			OnFileSave();

			if (m_bModified)
			{
				return FALSE;
			}
		}
		else if (nResponse == IDCANCEL)
		{
			return FALSE;
		}
	}

	ClearDocument();
	return TRUE;
}


void CFileManager::OnFileNew()
{
	CreateNew();
}

void CFileManager::OnFileOpen()
{
	CFileDialog fd(
		TRUE,
		_T("rc"),
		NULL,
		OFN_CREATEPROMPT |
		OFN_EXPLORER |
		OFN_FILEMUSTEXIST |
		OFN_HIDEREADONLY |
		OFN_NOREADONLYRETURN |
		OFN_PATHMUSTEXIST
		);
	if (fd.DoModal() != IDOK)
	{
		return;
	}

	if (CreateNew())
	{
		CString strScriptPath = fd.GetPathName();
		CString strHeaderPath = GetFolderPath(strScriptPath) + _T("Resource.h");

		if (!m_ScriptFile.Open(strScriptPath, CFile::shareDenyWrite | CFile::modeReadWrite) ||
			!m_HeaderFile.Open(strHeaderPath, CFile::shareDenyRead | CFile::modeReadWrite))
		{
			AfxMessageBox(AFX_IDP_FAILED_INVALID_PATH, MB_ICONERROR);
			return;
		}

		m_strTitle = m_ScriptFile.GetFileTitle();
		m_rDocument.Load(m_ScriptFile, m_HeaderFile);
	}
}

void CFileManager::OnFileSave()
{
	if (m_bNamed)
	{
		m_rDocument.Save(m_ScriptFile, m_HeaderFile);
	}
	else
	{
		OnFileSaveAs();
	}
}

void CFileManager::OnFileSaveAs()
{
	CFileDialog fd(FALSE);
	if (fd.DoModal() == IDOK)
	{
	}
}
